<template>
    <div v-if="visible" class="relation-dialog-mask">
        <div class="relation-dialog-content">
            <div class="dialog-header">
                <div :class="['tab', {active: activeTab==='self'}]" @click="activeTab='self'">关联本课</div>
                <div :class="['tab', {active: activeTab==='other'}]" @click="activeTab='other'">关联其他课</div>
                <span class="close-btn" @click="$emit('close')">×</span>
            </div>
            <div class="dialog-body">
                <div class="left-tree">
                    <div class="tree-title">共 {{ allNodes ? allNodes.length : 0 }} 个分类/知识点</div>
                    <input class="search-box" v-model="search" placeholder="搜索" />
                    <div class="tree-list">
                        <RelationTree :nodes="rootNodes" :all-nodes="allNodes" :selected-id="selectedId"
                            @select="selectNode" @choose-relation="chooseRelation"
                            @open-relation-menu="openRelationMenu" />
                    </div>
                </div>
                <div class="right-relations">
                    <div class="relation-group">
                        <div class="relation-title">前置({{ prerequisites ? prerequisites.length : 0 }})</div>
                        <div class="relation-list">
                            <template v-if="prerequisites && prerequisites.length">
                                <div v-for="id in prerequisites" :key="id" class="relation-item">
                                    {{ getNodeName(id) }}
                                    <span class="remove-btn" @click="removeRelation('prerequisite', id)">×</span>
                                </div>
                            </template>
                            <template v-else>无</template>
                        </div>
                    </div>
                    <div class="relation-group">
                        <div class="relation-title">后置({{ postrequisites ? postrequisites.length : 0 }})</div>
                        <div class="relation-list">
                            <template v-if="postrequisites && postrequisites.length">
                                <div v-for="id in postrequisites" :key="id" class="relation-item">
                                    {{ getNodeName(id) }}
                                    <span class="remove-btn" @click="removeRelation('postrequisite', id)">×</span>
                                </div>
                            </template>
                            <template v-else>无</template>
                        </div>
                    </div>
                    <div class="relation-group">
                        <div class="relation-title">关联({{ relations ? relations.length : 0 }})</div>
                        <div class="relation-list">
                            <template v-if="relations && relations.length">
                                <div v-for="id in relations" :key="id" class="relation-item">
                                    {{ getNodeName(id) }}
                                    <span class="remove-btn" @click="removeRelation('relation', id)">×</span>
                                </div>
                            </template>
                            <template v-else>无</template>
                        </div>
                    </div>
                </div>
            </div>
            <div class="dialog-footer">
                <button class="cancel-btn" @click="$emit('close')">取消</button>
                <button class="ok-btn" @click="saveRelations">确定</button>
            </div>
        </div>
        <div v-if="relationMenuNodeId" class="relation-menu"
            :style="{ left: menuPosition.x + 'px', top: menuPosition.y + 'px' }" @click.stop>
            <div class="menu-item" @click="setRelation('prerequisite')">设为前置</div>
            <div class="menu-item" @click="setRelation('postrequisite')">设为后置</div>
            <div class="menu-item" @click="setRelation('relation')">关联关系</div>
        </div>
    </div>
</template>

<script setup>
    import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
    import RelationTree from './RelationTree.vue'
    const props = defineProps({
        visible: Boolean,
        node: Object,
        allNodes: Array
    })
    const activeTab = ref('self')
    const search = ref('')
    const selectedId = ref('')
    const relationMenuNodeId = ref(null)
    const menuPosition = ref({ x: 0, y: 0 })
    const prerequisites = ref([])
    const postrequisites = ref([])
    const relations = ref([])
    const emit = defineEmits(['close', 'ok'])

    const rootNodes = computed(() =>
        (props.allNodes || []).filter(item => item.parentId === null)
    )
    function selectNode(node) {
        selectedId.value = node.id
    }
    function chooseRelation(node) {
        // 这里后续实现关系类型选择浮层
        // console.log('选择关系', node)
    }
    function openRelationMenu(node, event) {
        relationMenuNodeId.value = node.id
        // 计算菜单位置（相对于页面）
        const rect = event.target.getBoundingClientRect()
        menuPosition.value = { x: rect.right + 8, y: rect.top }
        // 阻止冒泡
        event.stopPropagation()
    }
    function closeRelationMenu() {
        relationMenuNodeId.value = null
    }
    // 点击空白关闭菜单
    document.addEventListener('click', closeRelationMenu)
    onBeforeUnmount(() => {
        document.removeEventListener('click', closeRelationMenu)
    })
    function setRelation(type) {
        const id = relationMenuNodeId.value
        if (!id) return
        if (type === 'prerequisite' && !prerequisites.value.includes(id)) {
            prerequisites.value.push(id)
        } else if (type === 'postrequisite' && !postrequisites.value.includes(id)) {
            postrequisites.value.push(id)
        } else if (type === 'relation' && !relations.value.includes(id)) {
            relations.value.push(id)
        }
        closeRelationMenu()
    }
    function removeRelation(type, id) {
        if (type === 'prerequisite') {
            prerequisites.value = (prerequisites.value || []).filter(item => item !== id)
        } else if (type === 'postrequisite') {
            postrequisites.value = (postrequisites.value || []).filter(item => item !== id)
        } else if (type === 'relation') {
            relations.value = (relations.value || []).filter(item => item !== id)
        }
    }
    function getNodeName(id) {
        const node = (props.allNodes || []).find(n => n.id === id)
        return node ? node.name : id
    }
    // 监听 node 变化，初始化关系数组
    watch(() => props.node, (newNode) => {
        if (newNode) {
            prerequisites.value = Array.isArray(newNode.prerequisites) ? [...newNode.prerequisites] : []
            postrequisites.value = Array.isArray(newNode.postrequisites) ? [...newNode.postrequisites] : []
            relations.value = Array.isArray(newNode.relations) ? [...newNode.relations] : []
        }
    }, { immediate: true })

    function saveRelations() {
        if (props.node) {
            props.node.prerequisites = [...prerequisites.value]
            props.node.postrequisites = [...postrequisites.value]
            props.node.relations = [...relations.value]
        }
        emit('close') // 通知父组件关闭弹窗
    }
</script>

<style scoped>
    .relation-dialog-mask {
        position: fixed;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.2);
        z-index: 1000;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .relation-dialog-content {
        background: #fff;
        border-radius: 10px;
        padding: 0;
        min-width: 700px;
        min-height: 420px;
        box-shadow: 0 2px 16px #aaa;
        display: flex;
        flex-direction: column;
    }

    .dialog-header {
        display: flex;
        align-items: center;
        border-bottom: 1px solid #f0f0f0;
        padding: 18px 24px 0 24px;
        position: relative;
    }

    .tab {
        font-size: 16px;
        margin-right: 32px;
        padding-bottom: 8px;
        cursor: pointer;
        color: #888;
        border-bottom: 2px solid transparent;
        transition: color 0.2s, border 0.2s;
    }

    .tab.active {
        color: #3a7afe;
        border-bottom: 2px solid #3a7afe;
    }

    .close-btn {
        position: absolute;
        right: 18px;
        top: 10px;
        font-size: 22px;
        color: #bbb;
        cursor: pointer;
    }

    .dialog-body {
        display: flex;
        flex: 1;
        padding: 18px 24px 0 24px;
    }

    .left-tree {
        width: 340px;
        border-right: 1px solid #f0f0f0;
        padding-right: 18px;
    }

    .tree-title {
        font-size: 14px;
        color: #888;
        margin-bottom: 8px;
    }

    .search-box {
        width: 100%;
        padding: 6px 10px;
        border-radius: 6px;
        border: 1px solid #e0e0e0;
        margin-bottom: 12px;
        font-size: 14px;
    }

    .tree-list {
        min-height: 180px;
        background: #f8fafd;
        border-radius: 6px;
        padding: 10px;
        color: #bbb;
        text-align: center;
    }

    .right-relations {
        flex: 1;
        padding-left: 32px;
        display: flex;
        flex-direction: column;
        gap: 18px;
    }

    .relation-group {
        background: #f8fafd;
        border-radius: 6px;
        padding: 10px 14px;
    }

    .relation-title {
        font-size: 14px;
        color: #3a7afe;
        margin-bottom: 6px;
    }

    .relation-list {
        min-height: 24px;
        color: #888;
    }

    .dialog-footer {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding: 18px 32px 18px 0;
        border-top: 1px solid #f0f0f0;
        background: #fff;
    }

    .cancel-btn {
        background: #f7f9fa;
        color: #888;
        border: none;
        border-radius: 6px;
        padding: 8px 24px;
        font-size: 15px;
        margin-right: 18px;
        cursor: pointer;
    }

    .ok-btn {
        background: #3a7afe;
        color: #fff;
        border: none;
        border-radius: 6px;
        padding: 8px 32px;
        font-size: 15px;
        cursor: pointer;
    }

    .relation-menu {
        position: fixed;
        z-index: 2000;
        min-width: 120px;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 12px #d0d8e0;
        padding: 8px 0;
        font-size: 15px;
        color: #222;
        margin-top: 2px;
    }

    .menu-item {
        padding: 8px 18px;
        cursor: pointer;
        transition: background 0.2s;
    }

    .menu-item:hover {
        background: #f0f6ff;
    }

    .relation-item {
        display: inline-block;
        background: #eaf2ff;
        color: #3a7afe;
        border-radius: 4px;
        padding: 2px 10px 2px 8px;
        margin: 0 8px 6px 0;
        font-size: 14px;
        position: relative;
    }

    .remove-btn {
        color: #bbb;
        margin-left: 6px;
        cursor: pointer;
        font-weight: bold;
        font-size: 15px;
        transition: color 0.2s;
    }

    .remove-btn:hover {
        color: #ff4d4f;
    }
</style>